package com.tw.wechart2;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tw.wechart2.adapter.TweetsAdapter;
import com.tw.wechart2.bean.Comment;
import com.tw.wechart2.bean.Tweet;
import com.tw.wechart2.constant.Constant;
import com.tw.wechart2.listener.RecyclerStateListener;
import com.tw.wechart2.listener.RequestResponseCallback;
import com.tw.wechart2.util.MyLogUtils;
import com.tw.wechart2.util.RequestResponseUtil;
import com.tw.wechart2.view.RecyclerView2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener {

    private String TAG = MainActivity.class.getSimpleName();
    private Context context;

    private TextView tv_refresh;
    private ImageView iv_back;
    private RecyclerView2 rv_tweets;
    // rv_tweets布局
    private LinearLayoutManager manager;

    // tweet列表
    private List<Tweet> listTweets = new ArrayList<>();
    private TweetsAdapter adapter;

    // 下拉刷新时初始位置(距离屏幕顶部)
    private float startY = 0;

    private boolean isInitMore = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        initView();
        initListener();
        initData();
    }

    private void initView() {
        tv_refresh = findViewById(R.id.tv_refresh);
        iv_back = findViewById(R.id.iv_back);
        rv_tweets = findViewById(R.id.rv_tweets);
    }

    private void initListener() {
        iv_back.setOnClickListener(this);
        // 刷新监听
        rv_tweets.setOnStateListener(new RecyclerStateListener() {
            @Override
            public void refreshData() {
                // 获取tweet内容
                initData();
            }
        });
        // 加载更多监听
        rv_tweets.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && manager.findLastVisibleItemPosition() == adapter.getDataSize()) {
                    if (isInitMore) {
                        return;
                    }
                    // 加载更多
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 正在加载
                            isInitMore = true;
                            // 手动等待1S中
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            if (adapter.getDataSize() < listTweets.size()) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        adapter.initMore();
                                        MyLogUtils.instance().logI(TAG, "加载更多, " + listTweets.size() + ";;" + adapter.getDataSize());
                                    }
                                });
                            }
                            // 加载完毕
                            isInitMore = false;
                        }
                    }).start();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void initData() {
        // 获取用户信息
        getUserInfo();
    }

    /**
     * @Description: 获取用户信息
     * @Author: lanteng 2020/9/16
     * @return
     */
    private void getUserInfo() {
        Toast.makeText(context, "开始加载数据,请稍后...", Toast.LENGTH_SHORT).show();
        JSONObject obj = new JSONObject();
        RequestResponseUtil.getInstance().getRequestJSONPost(this, obj, Constant.USER_INFO, 0, 0, new RequestResponseCallback() {
            @Override
            public void onFailure(String str) {
                MyLogUtils.instance().logE(TAG, str);
                Toast.makeText(context, "用户信息请求失败", Toast.LENGTH_SHORT).show();

                // 获取tweet内容
                getTweetsInfo();

                tv_refresh.setVisibility(View.VISIBLE);
            }

            @Override
            public void onSuccess(String body) {
                try {
                    JSONObject obj = new JSONObject(body);
                    Tweet tweet = new Tweet();
                    // 显示头像
                    tweet.setBigHead(obj.getString("avatar"));
                    tweet.setSmallHead(obj.getString("avatar"));
                    // 显示昵称
                    tweet.setUserName(obj.getString("nick"));
                    listTweets.add(tweet);
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(context, "用户信息请求失败", Toast.LENGTH_SHORT).show();
                    MyLogUtils.instance().logE(TAG, e.toString());
                }
                MyLogUtils.instance().logI(TAG, body);

                // 获取tweet内容
                getTweetsInfo();

                tv_refresh.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * @Description: 获取tweet内容
     * @Author: lanteng 2020/9/16
     * @return
     */
    private void getTweetsInfo() {
        JSONObject obj = new JSONObject();
        RequestResponseUtil.getInstance().getRequestJSONPost(this, obj, Constant.TWEETS_INFO, 0, 0, new RequestResponseCallback() {
            @Override
            public void onFailure(String str) {
                MyLogUtils.instance().logE(TAG, str);
                Toast.makeText(context, "朋友圈信息请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String body) {
                Toast.makeText(context, "数据加载完成", Toast.LENGTH_SHORT).show();
                try {
                    JSONArray array = new JSONArray(body);
                    // 清空旧tweet列表
                    if (null != listTweets && listTweets.size() > 0) {
                        listTweets = listTweets.subList(0, 1);
                    }
                    for (int i=0; i<array.length(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        // 筛选逻辑:
                        // 1. 发送人必须有
                        // 2. 没有内容和图片的忽略
                        if (null != obj && obj.has("sender") && (obj.has("content") || obj.has("images"))) {
                            Tweet tweet = new Tweet();
                            // 获取用户信息(部分字段是否存在判断略)
                            tweet.setSenderUserName(obj.getJSONObject("sender").getString("username"));
                            tweet.setSenderNick(obj.getJSONObject("sender").getString("nick"));
                            tweet.setSenderAvatar(obj.getJSONObject("sender").getString("avatar"));

                            if (obj.has("content")) {
                                // 如果有tweet内容则获取tweet内容
                                tweet.setContent(obj.getString("content"));
                            }

                            if (obj.has("images")) {
                                // 如果有图片信息则获取图片信息(部分字段是否存在判断略)
                                List<String> listImages = new ArrayList<>();
                                JSONArray array1 = obj.getJSONArray("images");
                                for (int j=0; j<array1.length(); j++) {
                                    listImages.add(array1.getJSONObject(j).getString("url"));
                                }

                                tweet.setListImages(listImages);
                            }

                            if (obj.has("comments")) {
                                // 如果有评论信息则获取评论信息(部分字段是否存在判断略)
                                List<Comment> listComment = new ArrayList<>();
                                JSONArray array1 = obj.getJSONArray("comments");
                                for (int j=0; j<array1.length(); j++) {
                                    Comment comment = new Comment();
                                    comment.setContent(array1.getJSONObject(j).getString("content"));

                                    comment.setSenderUserName(array1.getJSONObject(j).getJSONObject("sender").getString("username"));
                                    comment.setSenderNick(array1.getJSONObject(j).getJSONObject("sender").getString("nick"));
                                    comment.setSenderAvatar(array1.getJSONObject(j).getJSONObject("sender").getString("avatar"));
                                    listComment.add(comment);
                                }
                                tweet.setListComment(listComment);
                            }
                            // 将tweet对象添加到tweet集合中
                            listTweets.add(tweet);
                        }
                    }
                    // 刷新tweet
                    adapter = new TweetsAdapter(context, listTweets, 6);
                    manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
                    rv_tweets.setLayoutManager(manager);
                    rv_tweets.setAdapter(adapter);
                    // 初始化布局对象
                    rv_tweets.initLinearLayoutManager();
                    rv_tweets.setDataSize(adapter.getDataSize());
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(context, "朋友圈信息请求失败", Toast.LENGTH_SHORT).show();
                    MyLogUtils.instance().logE(TAG, e.toString());
                }
                MyLogUtils.instance().logI(TAG, body);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_user_name) {
            Toast.makeText(context, "ok", Toast.LENGTH_SHORT).show();
        }
    }
}
